
#include"SList.h"

//生成一个新的结点，并返回其地址
SLT* SLTBuyNode(SLTDateType x)
{	
	SLT* newnode = (SLT*)malloc(sizeof(SLT));
	if(!newnode)
	{
		perror("malloc mistake");
		exit(-1);
	}
	newnode->date = x;
	newnode->next = NULL;
	return newnode;
}
// SLT push & pop
void SLTPushBack(SLT** pphead,SLTDateType x)
{
	assert(pphead);
	SLT* newnode =  SLTBuyNode(x);
	//1.此链表为空表的时候
	if(*pphead == NULL)
		*pphead = newnode;
	else//2.先找到尾结点，再插入
	{
		SLT* cur = *pphead;
		while(cur->next)
		{
			cur = cur->next;
		}
		cur->next = newnode;
	}
}
void SLTPushFront(SLT** pphead,SLTDateType x)
{
	assert(pphead);
	SLT* newnode = SLTBuyNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void SLTPopBack(SLT** pphead)
{
	//pphead不能为空 & 不能是空表
	assert(pphead && *pphead);
	//只有一个结点的情况
	if((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
 	 //找到尾结点和前一个结点 
	 SLT* cur = *pphead;
	 SLT* prev = NULL; 
	 while(cur->next)
	 {
		 prev = cur;
		 cur = cur->next;
	 }
	 free(cur);
	 cur = NULL;
	 prev->next = NULL;
	}

}
void SLTPopFront(SLT** pphead)
{
	//老规矩
	assert(pphead && *pphead);

	SLT* tmp = (*pphead)->next;
	free(*pphead);
	*pphead = tmp;
}
// SLT Find
SLT* SLTFind(SLT* phead,SLTDateType x)
{
	SLT* cur = phead;
	while(cur)
	{
		if (0 == memcmp(&cur->date, &x, sizeof(SLTDateType)))
			return cur;
		cur = cur->next;
	}
	return NULL;
}
// SLT Insert pos front & back 
void SLTInsert(SLT** pphead,SLT* pos,SLTDateType x)
{
	assert(pphead && *pphead && pos);
	if((*pphead) == pos)
	{
		SLTPushFront(pphead,x);
	}
	else
	{
		SLT* newnode = SLTBuyNode(x);
		SLT*cur = *pphead;
		while(cur->next != pos)
		{
			cur = cur->next;
		}
		newnode->next = pos;
		cur->next = newnode;
	}
}
void SLTInsertAfter(SLT* pos,SLTDateType x)
{
	assert(pos);
	SLT* newnode = SLTBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
// SLT Embrase pos & back
void SLTEmbrase(SLT** pphead,SLT* pos)
{
	
	assert(pphead && *pphead && pos);
	//1.pos为链表的第一个结点时：
	if( *pphead == pos )
	{
		//类似于头删;
		SLTPopFront(pphead);
	}
	else
	{
		//遍历->找到pos结点的前一个结点;
		SLT* cur = *pphead;
		while(cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SLTEmbraseAfter(SLT* pos)
{
	assert(pos);
	if(pos->next == NULL)
	{
		perror("mistake");
		return;
	}

	SLT* tmp = pos->next;
	pos->next = tmp->next;
	free(tmp);	
	tmp = NULL;
}
// SLT Modify
void SLTModify(SLT* pos,SLTDateType x)
{
	assert(pos);
	pos->date = x;
}
// SLT Destory
void SLTDestory(SLT** pphead)
{
	assert(pphead);
	SLT* cur = *pphead;
	while(cur)
	{
		SLT* tmp = cur->next;
		free(cur);
		cur = tmp;
	}
	*pphead = NULL;
}
























